import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElFormItem,
  ElInput,
  ElButton,
  ElSpace,
  ElLink,
  ElMessage,
  ElMessageBox,
  ElDialog
} from 'element-plus'
// import { Plus } from '@element-plus/icons-vue'

import type { sendDevType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'

import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import styles from '../../index.module.scss'
import useVuexGetters from '~/hooks/useVuexGetters'
import useWebsocket from '~/hooks/useWebsocket'
import CallDataTable from './callDataTable'
import NoticeMes from '../../components/noticeMes'

// 单灯设备管理
export default defineComponent({
  props: ['detail', 'cancel', 'status'],
  setup(props) {
    const store = useStore()
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const formValues = reactive<sendDevType>({})
    const userState = useVuexGetters('user', ['token'])
    const webSocketRef = useWebsocket('/websocket/protocol/lampctrl', {
      // // 接收数据回调
      onmessage: () => {}
    })
    const noticeRef = ref()
    const state: any = reactive({
      callDataVisible: false
    })
    const columns: TableColumnProps<sendDevType>[] = [
      {
        label: '单灯名称',
        prop: 'lampNodeName',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '单灯编号',
        prop: 'lampNodeCode',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '设备型号',
        prop: 'modelName',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '设备品牌',
        prop: 'brandName',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '所属分组',
        prop: 'groupName',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '下发时间',
        prop: 'sendDate',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '下发内容',
        prop: 'sendContent',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '下发人',
        prop: 'sendBy',
        minWidth: 140,
        align: 'center',
        showOverflowTooltip: true,
        sortable: true,
        disabled: true
      },
      {
        label: '操作',
        prop: 'options',
        minWidth: 200,
        align: 'center',
        fixed: 'right',
        disabled: true,
        render: ({ row }) => (
          <ElSpace>
            <ElLink type="primary" onClick={() => sendMulTask(row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 下发策略
            </ElLink>
            <ElLink type="primary" onClick={() => callTask(row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 召测计划
            </ElLink>
          </ElSpace>
        )
      }
    ]

    const filterType = (type: number) => {
      switch (type) {
        case 0:
          return '待下发'
        case 1:
          return '成功'
        case 2:
          return '失败'
        default:
          return ''
      }
    }

    const sendMulTask = (record?: sendDevType) => {
      if (!record && !proSaasTableRef.value!.selecteds?.length) {
        ElMessage({ type: 'warning', message: '请选择要下发的设备' })
        return
      }
      const params =
        record?.lampNodeId ||
        proSaasTableRef.value!.selecteds?.map?.((item) => item!?.lampNodeId)?.join(',')
      ElMessageBox({
        title: '确认提示',
        message: (
          <section class={styles['delete-confirm-box']}>
            {<p class="delete-title">确认给选中设备下发策略？</p>}
          </section>
        ),
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--primary is-plain',
        closeOnClickModal: false, // 点遮罩层不关弹窗
        draggable: true // 可拖拽
      })
        .then(async () => {
          const websockParams = {
            token: userState.token.value,
            deviceId: params,
            commandCode: '010'
          }
          await store.dispatch('singleLamp/SendTask', { lampNodeIds: params })
          webSocketRef.value!.send(JSON.stringify(websockParams))

          noticeRef.value.initMes({
            deviceId: params,
            commandCode: '010',
            token: userState.token.value,
            title: '下发数据',
            key: '010',
            // arrStr: data?.lampNodeCode,
            callBack: () => {}
          })
        })
        .catch(() => {})
    }
    // 召测计划
    const callTask = async (data: any) => {
      const websockParams = {
        token: userState.token.value,
        deviceId: data?.lampNodeCode,
        commandCode: '011'
      }
      await store.dispatch('singleLamp/CallLampPlan', { lampNodeId: data?.lampNodeId })
      webSocketRef.value!.send(JSON.stringify(websockParams))

      noticeRef.value.initMes({
        deviceId: data?.lampNodeId,
        commandCode: '011',
        token: userState.token.value,
        title: '召测数据',
        key: '011',
        arrStr: data?.lampNodeCode,
        callBack: () => {}
      })
    }
    // 收到websocket消息
    const swInitFun = (data?: any) => {
      // console.log(data);

      if (data.data.status === 1) {
        if (data.data.content) {
          state.callDataVisible = true
          state.callData = JSON.parse(data.data.content)
        }
        noticeRef.value.stateFun({
          key: data.commandCode,
          state: 'success',
          errText: data.data.message || '命令下发失败！'
        })
      } else {
        noticeRef.value.stateFun({
          key: data.commandCode,
          state: 'error',
          errText: data.data.message || '命令下发失败！'
        })
        return false
      }
    }
    const closeTable = () => {
      state.callDataVisible = false
    }
    onMounted(() => {
      nextTick(proSaasTableRef.value?.toSearch)
      window.swInitFun = swInitFun
    })
    // 离开前 先断开websocket连接
    // onUnmounted(() => {
    //   webSocketRef.value?.close()
    // })
    // 按回车搜索列表
    const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
      if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
    }
    // 清空搜索
    const clearSearchTable = async () => {
      setTimeout(() => {
        proSaasTableRef.value!?.toSearch()
      }, 100)
    }
    return () => (
      <ElDialog
        title={`策略${filterType(props.status)}设备`}
        modelValue={true}
        beforeClose={props.cancel}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        width={1360}
      >
        {
          <ProSaasTable<sendDevType>
            tableId="monitor_sendDev"
            ref={proSaasTableRef}
            columns={columns}
            hasSelection
            dispatchType="singleLamp/GetTaskDeviceListPage"
            searchFormProps={{
              model: formValues
            }}
            searchParams={{
              lampTaskId: props.detail.id,
              sendState: props.status
            }}
            headerTitle={
              <>
                <ElButton type="primary" onClick={() => sendMulTask()}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 批量下发策略
                </ElButton>
              </>
            }
            searchformResponsiveCol={[
              <ElFormItem key="keyword" prop="keyword" label="">
                <ElInput
                  v-model={formValues.keyword}
                  placeholder="设备名称"
                  clearable
                  onKeydown={handleKeyDownEnterSubmitForm}
                  onClear={clearSearchTable}
                />
              </ElFormItem>
            ]}
          />
        }
        {state.callDataVisible && <CallDataTable data={state.callData} cancel={closeTable} />}
        <NoticeMes ref={noticeRef} />
      </ElDialog>
    )
  }
})
